<?php

namespace app\common\model;

use think\Model;
use app\common\traits\model\TraitModel;
/**
 * 评论模型
 */
abstract class Comments extends Model
{
    use TraitModel;

    protected $table = 'comments';

    public function replys()
    {
        return $this->hasMany('Comments', 'reply_id');
    }

    /**
     * 创建评论
     * @param  [type] $comment_info [description]
     * @return [type]               [description]
     */
    public function commentCreate($comment_info)
    {
    	return $this->create($comment_info, true);
    }
    /**
     * 修改评论信息
     * @param  [type] $comment_info [description]
     * @param  [type] $comment_id   [description]
     * @return [type]               [description]
     */
    public function commentUpdate($comment_info, $comment_id = null)
    {
        $comment_id = $comment_id ? : $comment_info['id'];
        return $this->update($comment_info, ['id' => $comment_id], true);
    }
    /**
     * 评论回复
     * @param  [type] $comment_info [description]
     * @return [type]               [description]
     */
    public function commentReply($comment_info)
    {
    	return $this->commentCreate($comment_info);
    }
    /**
     * 删除评论 同时删除回复信息
     * @param  [type] $comment_id [description]
     * @return [type]             [description]
     */
    public function commentDestroy($comment_id)
    {
        $this->startTrans();
        try {
            $this->commentDelete($comment_id);
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            return false;
        }
    }
    /**
     * 递归删除评论信息
     * @param  [type] $comment_id [description]
     * @return [type]             [description]
     */
    protected function commentDelete($comment_id)
    {
        $this->destroy($comment_id);
        if ($replys = $this->where(['reply_id' => $comment_id])->select()) {
            foreach ($replys as $reply) {
                $this->commentDelete($reply->id);
            }
        }
    }
}
